package com.vrms.app.controller;

import com.vrms.app.aop.SystemControllerLog;
import com.vrms.app.entity.Administrators;
import com.vrms.app.tools.CommonResult;
import com.vrms.app.service.AdministratorsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/administrators")

@CrossOrigin //解决跨域访问问题，
public class AdministratorsController {
    @Resource
    private AdministratorsService administratorsService;

    @GetMapping("/listPage")
    @SystemControllerLog(description = "分页查询管理员信息")
    public CommonResult listPage(int page, int size, String username) {
        Map<String, Object> map = new HashMap();
        map.put("count", administratorsService.count(username));
        map.put("data", administratorsService.listPage(page, size, username));
        return CommonResult.success(map);
    }

    @PostMapping("/save")
    @SystemControllerLog(description = "添加管理员信息")
    public CommonResult save(@RequestBody Administrators administrators) {
        return CommonResult.success(administratorsService.save(administrators));
    }

    @PostMapping("/update")
    @SystemControllerLog(description = "修改管理员信息")
    public CommonResult update(@RequestBody Administrators administrators) {
        return CommonResult.success(administratorsService.update(administrators));
    }

//    @PostMapping("/changeStats")
//    @SystemControllerLog(description = "改变用户状态")
//    public CommonResult changeStats(@RequestBody Administrators administrators) {
//        return CommonResult.success(administratorsService.changeStats(administrators));
//    }

    @PostMapping("/remove")
    @SystemControllerLog(description = "根据ID删除管理员信息")
    public CommonResult remove(Integer aid) {
        return CommonResult.success(administratorsService.remove(aid));

    }

    @SystemControllerLog(description = "登录")
    @GetMapping("/login")
    public CommonResult login(String username, String password) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                subject.login(token);//该方法是shiro提供的登录方法，该方法会自动跳转到用户定义的Realm中
            }
        } catch (AuthenticationException uae) {
            System.out.println("用户名称或者密码不正确");
            return CommonResult.failed();
        }
        return CommonResult.success(username);//登录成功返回username
    }

    @GetMapping("/logout")
    public CommonResult logout() {
        SecurityUtils.getSubject().logout();
        return CommonResult.success(200);
    }

}

